#include"SltNode.h"

SLTNode* NewSLTNode(SLTDataType x)
{
	SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
	if (newnode == NULL)
	{
		perror("malloc error");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;


	return newnode;
}

void SLTNodePrintf(SLTNode* ps)
{
	SLTNode* cur = ps;
	while (cur)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}

void SLTPushBack(SLTNode** pphead, SLTDataType x)
{

	SLTNode* newnode = NewSLTNode(x);
	//没有节点  改变plist(plist是结构体指针，需要结构体指针的指针，即二级指针)
	if (*pphead == NULL)
	{
		*pphead = newnode;//将plist指向头结点
	}
	else//有一个以上得结点
	{
		SLTNode* tail = *pphead;
		while (tail->next != NULL)
		{
			tail = tail->next;
		}
		//连接新节点 新节点->next已经在NewSLTNode置为NULL
		//改变的是结构体成员，结构体指针即可
		tail->next = newnode;
	}
}


void SLTPushFront(SLTNode** pphead, SLTDataType x)
{

	SLTNode* newnode = NewSLTNode(x);
	//连接新结点
	newnode->next = *pphead;
	*pphead = newnode;
}


//��?
void SLTPopBack(SLTNode** pphead)
{
	assert(*pphead);
	if ((*pphead)->next == NULL)//只有一个结点
	{
		free(*pphead);
		*pphead = NULL;
	}
	else//有一个以上得结点
	{
		SLTNode* tail = *pphead;
		SLTNode* tailPrev = NULL;//记录tail前一个
		//找尾
		while (tail->next != NULL)
		{
			tailPrev = tail;
			tail = tail->next;
		}
		free(tail);
		tailPrev->next = NULL;//成为新的尾节点
	}
}

void SLTPopFront(SLTNode** pphead)
{
	assert(*pphead);
	//一个节点和多个节点逻辑一样
	SLTNode* newhead = (*pphead)->next;
	free(*pphead);
	*pphead = newhead;
}

SLTNode* SLTNodeFind(SLTNode* phead, SLTDataType x)
{
	assert(phead);
	SLTNode* cur = phead;
	while (cur)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

//在pos位置插入
void SLTInsert(SLTNode** pphead, SLTNode* pos, SLTDataType x)
{
	assert(*pphead);
	assert(pos);
	SLTNode* newnode = NewSLTNode(x);
	if (*pphead == pos)
	{
		//头插
		SLTPushFront(pphead, x);
	}
	else
	{
		//找pos前一个
		SLTNode* posprev = *pphead;
		while (posprev->next != pos)
		{
			posprev = posprev->next;
		}
		posprev->next = newnode;
		newnode->next = pos;
	}
}

//在pos之后插入
void SLTInsertAfter(SLTNode* pos, SLTDataType x)
{
	assert(pos);
	SLTNode* newnode = NewSLTNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}

void SLTErase(SLTNode** pphead, SLTNode* pos)
{
	assert(*pphead);
	assert(pos);
	if (pos == *pphead)
	{
		//头删
		SLTPopFront(pphead);
	}

	else
	{
		//找pos前一个
		SLTNode* posprev = *pphead;
		while (posprev->next != pos)
		{
			posprev = posprev->next;
		}
		posprev->next = pos->next;
		free(pos);
		pos = NULL;
	}
}



void SLTEraseAfter(SLTNode* pos)
{
	assert(pos);
	assert(pos->next);//pos如果是尾  则删除无意义
	SLTNode* posNext = pos->next;
	pos->next = posNext->next;
	free(posNext);
	posNext = NULL;
}
